using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using Common;
using MainView.MainControls;
using Microsoft.Win32;
using SExperiment;
using SSettings;

namespace MainView.Windows
{
	public partial class QuickExperimentManageWindow : Window, IComponentConnector
	{
		public delegate void DelegateManageChangedEvent(object sender, EventArgs e);

		private CollectionViewSource view = new CollectionViewSource();

		public ObservableCollection<QuickExperimentData> QuickExperiments { get; set; }

		public event DelegateManageChangedEvent OnManageChanged;

		public QuickExperimentManageWindow()
		{
			InitializeComponent();
			AddHandler(QuickExperimentControl.OnQuickExperimentConrtolChangedRoutedEvent, new RoutedEventHandler(QuickExperimentConrtolChanged), true);
			base.Loaded += QuickExperimentManageWindow_Loaded;
		}

		private void QuickExperimentManageWindow_Loaded(object sender, RoutedEventArgs e)
		{
			Init();
		}

		public void Init()
		{
			QuickExperiments = ConfigSettings.GetInstance().QuickExperimentDatas;
			DirectoryInfo directoryInfo = new DirectoryInfo(Utility.GetExperimentTemplatePath());
			FileInfo[] files = directoryInfo.GetFiles();
			foreach (FileInfo fileInfo in files)
			{
				if (fileInfo.Extension.Equals(Experiment.FileTemplateDotExt))
				{
					QuickExperimentData quickExperimentData = QuickExperiments.Where((QuickExperimentData s) => s.QuickExperimentName.Equals(fileInfo.FullName)).FirstOrDefault();
					if (quickExperimentData == null)
					{
						quickExperimentData = new QuickExperimentData();
						quickExperimentData.QuickExperimentName = fileInfo.FullName;
						Experiment experiment = Experiment.LoadTemplate(fileInfo.FullName, false);
						quickExperimentData.Experiment = experiment;
						QuickExperiments.Add(quickExperimentData);
					}
				}
			}
			List<QuickExperimentData> list = new List<QuickExperimentData>();
			foreach (QuickExperimentData quickExperiment in QuickExperiments)
			{
				if (!File.Exists(quickExperiment.QuickExperimentName))
				{
					list.Add(quickExperiment);
				}
			}
			if (list.Count() > 0)
			{
				foreach (QuickExperimentData item in list)
				{
					QuickExperiments.Remove(item);
				}
				if (this.OnManageChanged != null)
				{
					this.OnManageChanged(this, new EventArgs());
				}
			}
			view.Source = QuickExperiments;
			view.View.SortDescriptions.Add(new SortDescription("Index", ListSortDirection.Ascending));
			windowQuickExperimentNameList.ItemsSource = view.View;
			ucWellPlate.SetContextMenu_Disable();
		}

		public void RefreshList(bool refreshSelected = true)
		{
			view.View.Refresh();
			if (refreshSelected && windowQuickExperimentNameList.Items.Count > 0 && windowQuickExperimentNameList.SelectedItem == null)
			{
				windowQuickExperimentNameList.SelectedItem = windowQuickExperimentNameList.Items[0];
			}
		}

		private void QuickExperimentConrtolChanged(object sender, RoutedEventArgs e)
		{
			if (this.OnManageChanged != null)
			{
				this.OnManageChanged(this, new EventArgs());
			}
		}

		private void CommandBinding_Delete_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			if (windowQuickExperimentNameList != null && windowQuickExperimentNameList.SelectedItems.Count == 1)
			{
				e.CanExecute = true;
			}
			else
			{
				e.CanExecute = false;
			}
		}

		private void CommandBinding_Delete_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (windowQuickExperimentNameList.SelectedItems.Count != 1)
			{
				return;
			}
			QuickExperimentData quickExperimentData = windowQuickExperimentNameList.SelectedItem as QuickExperimentData;
			if (System.Windows.MessageBox.Show(string.Format(Utility.GetMessage("msg_quickExperiment_delete_confirm"), Path.GetFileNameWithoutExtension(quickExperimentData.QuickExperimentName)), Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
			{
				if (File.Exists(quickExperimentData.QuickExperimentName))
				{
					File.Delete(quickExperimentData.QuickExperimentName);
				}
				QuickExperiments.Remove(quickExperimentData);
				if (this.OnManageChanged != null)
				{
					this.OnManageChanged(this, new EventArgs());
				}
			}
		}

		private void CommandBinding_Import_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
			openFileDialog.Title = Utility.GetMessage("quickExperiment_Memu_File_Import");
			openFileDialog.Filter = string.Format("{0}{1}|*.{2}", Experiment.FileTemplateExt, Utility.GetMessage("File"), Experiment.FileTemplateExt);
			openFileDialog.FileName = string.Empty;
			openFileDialog.FilterIndex = 1;
			openFileDialog.RestoreDirectory = true;
			openFileDialog.DefaultExt = Experiment.FileTemplateExt;
			openFileDialog.Multiselect = true;
			if (openFileDialog.ShowDialog() != true)
			{
				return;
			}
			bool flag = false;
			StringBuilder stringBuilder = new StringBuilder();
			string[] fileNames = openFileDialog.FileNames;
			foreach (string path in fileNames)
			{
				string tragetPath = Utility.GetExperimentTemplatePath() + Path.GetFileName(path);
				if (File.Exists(tragetPath))
				{
					if (System.Windows.MessageBox.Show(string.Format(Utility.GetMessage("msg_import_quickExperiment_exist"), Path.GetFileNameWithoutExtension(path)), Utility.GetMessage("quickExperiment_Memu_File_Import"), MessageBoxButton.YesNo) == MessageBoxResult.No)
					{
						continue;
					}
					File.Delete(tragetPath);
				}
				try
				{
					string sourceFileName = Path.Combine(Path.GetDirectoryName(path), Path.GetFileName(path));
					string destFileName = Path.Combine(Utility.GetExperimentTemplatePath(), Path.GetFileName(path));
					File.Copy(sourceFileName, destFileName, true);
					QuickExperimentData quickExperimentData = QuickExperiments.Where((QuickExperimentData s) => s.QuickExperimentName.Equals(tragetPath)).FirstOrDefault();
					if (quickExperimentData != null)
					{
						quickExperimentData.Experiment = Experiment.LoadTemplate(tragetPath, false);
						if (!quickExperimentData.IsShowInCanvas)
						{
							quickExperimentData.IsShowInCanvas = true;
							flag = true;
						}
						quickExperimentData.QuickExperimentName = tragetPath;
						continue;
					}
					quickExperimentData = new QuickExperimentData();
					quickExperimentData.Experiment = Experiment.LoadTemplate(tragetPath, false);
					quickExperimentData.QuickExperimentName = tragetPath;
					quickExperimentData.IsShowInCanvas = true;
					quickExperimentData.Index = ((QuickExperiments.Count > 0) ? (QuickExperiments.Max((QuickExperimentData s) => s.Index) + 1) : 0);
					QuickExperiments.Add(quickExperimentData);
					flag = true;
				}
				catch
				{
					if (stringBuilder.Length == 0)
					{
						stringBuilder.AppendLine(Utility.GetMessage("msg_quickExperiment_import_fail"));
					}
				}
			}
			if (flag)
			{
				RefreshList();
				if (this.OnManageChanged != null)
				{
					this.OnManageChanged(this, new EventArgs());
				}
			}
			if (stringBuilder.Length > 0)
			{
				System.Windows.MessageBox.Show(stringBuilder.ToString());
			}
		}

		private void CommandBinding_Import_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		private void CommandBinding_Export_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (windowQuickExperimentNameList.SelectedItems.Count != 1)
			{
				return;
			}
			QuickExperimentData quickExperimentData = windowQuickExperimentNameList.SelectedItem as QuickExperimentData;
			System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
			saveFileDialog.Filter = string.Format("{0}{1}|*.{2}", Experiment.FileTemplateExt, Utility.GetMessage("File"), Experiment.FileTemplateExt);
			saveFileDialog.FileName = Path.GetFileName(quickExperimentData.QuickExperimentName);
			saveFileDialog.FilterIndex = 1;
			saveFileDialog.InitialDirectory = Utility.GetMyDocumentFolder();
			saveFileDialog.DefaultExt = Experiment.FileTemplateExt;
			if (saveFileDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
			{
				return;
			}
			try
			{
				string sourceFileName = Path.Combine(Path.GetDirectoryName(quickExperimentData.QuickExperimentName), Path.GetFileName(quickExperimentData.QuickExperimentName));
				string destFileName = Path.Combine(Path.GetDirectoryName(saveFileDialog.FileName), Path.GetFileName(saveFileDialog.FileName));
				if (!Directory.Exists(Path.GetDirectoryName(saveFileDialog.FileName)))
				{
					Directory.CreateDirectory(Path.GetDirectoryName(saveFileDialog.FileName));
				}
				File.Copy(sourceFileName, destFileName, true);
				System.Windows.MessageBox.Show(Utility.GetMessage("msg_quickExperiment_export_sussess"));
			}
			catch
			{
				System.Windows.MessageBox.Show(Utility.GetMessage("msg_quickExperiment_export_fail"));
			}
		}

		private void CommandBinding_Rename_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (windowQuickExperimentNameList.SelectedItems.Count != 1)
			{
				return;
			}
			QuickExperimentData quickExperimentData = windowQuickExperimentNameList.SelectedItem as QuickExperimentData;
			Experiment experiment = (Experiment)quickExperimentData.Experiment;
			AddExperimentTemplateWindow addExperimentTemplateWindow = new AddExperimentTemplateWindow();
			addExperimentTemplateWindow.Owner = Utility.GetMainWindow();
			addExperimentTemplateWindow.Title = Utility.GetMessage("rename_quickExperiment");
			addExperimentTemplateWindow.fileName = Path.GetFileNameWithoutExtension(quickExperimentData.QuickExperimentName);
			addExperimentTemplateWindow.simpleName = ((experiment == null) ? string.Empty : experiment.Simple_Name);
			addExperimentTemplateWindow.remarkName = ((experiment == null) ? string.Empty : experiment.TemplateRemarks);
			addExperimentTemplateWindow.ImageBytes = experiment.Image;
			if (addExperimentTemplateWindow.ShowDialog() != true)
			{
				return;
			}
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(quickExperimentData.QuickExperimentName);
			string fileName = addExperimentTemplateWindow.fileName;
			string text = Utility.GetExperimentTemplatePath() + fileName + Experiment.FileTemplateDotExt;
			StringBuilder stringBuilder = new StringBuilder();
			if (fileNameWithoutExtension != fileName && File.Exists(text))
			{
				stringBuilder.Append(string.Format(Utility.GetMessage("msg_filename_is_repeat"), fileName));
			}
			if (stringBuilder.Length > 0)
			{
				System.Windows.MessageBox.Show(stringBuilder.ToString());
				return;
			}
			if (File.Exists(quickExperimentData.QuickExperimentName))
			{
				try
				{
					if (File.GetAttributes(quickExperimentData.QuickExperimentName).ToString().IndexOf("ReadOnly") != -1)
					{
						File.SetAttributes(quickExperimentData.QuickExperimentName, FileAttributes.Normal);
					}
					File.Delete(quickExperimentData.QuickExperimentName);
				}
				catch (Exception)
				{
				}
			}
			experiment.Simple_Name = addExperimentTemplateWindow.simpleName;
			experiment.TemplateRemarks = addExperimentTemplateWindow.remarkName;
			if (addExperimentTemplateWindow.ImageBytes != null && addExperimentTemplateWindow.ImageBytes.Length != 0)
			{
				experiment.Image = addExperimentTemplateWindow.ImageBytes;
			}
			experiment.SaveTemplate(text, false);
			quickExperimentData.QuickExperimentName = text;
		}
	}
}
